import config from '@/app.config.js'
const tokenKey = config.lzy.storageKey + '-token';
const domain = config.lzy.domain;

const utils = {
	//接口地址
	interfaceUrl: function() {
		return domain
	},
	delayed: null,
	toast: function(text, duration, success) {
		uni.showToast({
			title: text || "出错啦~",
			icon: success || 'none',
			duration: duration || 2000
		})
	},
	modal: function(title, content, showCancel = false, callback, confirmColor, confirmText, cancelColor, cancelText) {
		uni.showModal({
			title: title || '提示',
			content: content,
			showCancel: showCancel,
			cancelColor: cancelColor || "#555",
			confirmColor: confirmColor || "#e41f19",
			confirmText: confirmText || "确定",
			cancelText: cancelText || "取消",
			success(res) {
				if (res.confirm) {
					callback && callback(true)
				} else {
					callback && callback(false)
				}
			}
		})
	},
	toLogin(callback){
		let msg = '未登录或登录已过期，请重新登录';
		// 必须登录才能访问
		utils.modal('温馨提示', msg, true, (confirm) => {
			if (confirm) {
				vk.navigateTo({
					url: '/pages/login/login',
					events: {
						loginSuccess: () => {
							// console.log("util登录回调", vk.getVuex("$user.userInfo"));
							callback && callback();
						}
					}
				})
			} else {
				uni.navigateBack({
					delta: 1,
					fail: (res) => {
						uni.switchTab({
							url: '/pages/index/index',
						})
					}
				})
			}
		})
		return msg
	},
	/**
	 * 请求数据处理
	 * @param string url 请求地址 。支持输入完整的请求地址，以http或https开头。modify by LZy on 2023.8.13
	 * @param {*} postData 请求参数
	 * @param string method 请求方式
	 *  GET or POST
	 * @param string contentType 数据格式
	 *  'application/x-www-form-urlencoded'
	 *  'application/json'
	 * @param bool isDelay 是否延迟显示loading
	 * @param bool hideLoading 是否隐藏loading
	 *  true: 隐藏
	 *  false:显示
	 * @param string loadingTitle loading显示的文字
	 * @param function callback 回调函数。登录过期的场景，重新登录后要重新调用的页面取数据函数，如getData，getList等
	 */
	request: function(url, postData = {}, method = "GET", contentType = "application/x-www-form-urlencoded", isDelay, hideLoading, 
		loadingTitle, callback) {
		//接口请求
		let loadding = false;
		utils.delayed && uni.hideLoading();
		clearTimeout(utils.delayed);
		utils.delayed = null;
		if (!hideLoading) {
			utils.delayed = setTimeout(() => {
				uni.showLoading({
					mask: true,
					title: loadingTitle || '请稍候...',
					success(res) {
						loadding = true
					}
				})
			}, isDelay ? 1000 : 0)
		}
		// if(!contentType) contentType = "application/x-www-form-urlencoded";
		contentType = "application/json";
		
		
		// console.log('封装request-token', utils.getToken())	
		
		return new Promise((resolve, reject) => {
			if(!utils.getToken()){
				reject(utils.toLogin(callback));
			}else{
				let tokenStr = utils.getToken() ? 'Bearer ' + utils.getToken() : '';
				// console.log('封装request-tokenStr', tokenStr)
				uni.request({
					url: url.indexOf("http") == 0 ? url : (utils.interfaceUrl() + url),
					data: postData,
					header: {
						'content-type': contentType,
						'Authorization': tokenStr,
					},
					method: method, //'GET','POST'
					dataType: 'json',
					timeout: 15000,  // 15秒超时
					withCredentials: true,
					success: (res) => {
						// console.log('封装request success', res)
						if (res.statusCode === 200) {
							// 登录超时 add by LZy on 2023.7.17 
							if(res.data.code === 401){ // 认证失败，无法访问系统资源 401
								reject(utils.toLogin(callback));
							} else {
								resolve(res.data);
							}
						} else {
							// console.log('封装request success statusCode=' + res.statusCode, res)
							// reject(res.data.msg);
							// reject(res.data.msg || res.statusCode);
							reject(res);
							/* 错误码
							接口不通 404
							超时
							*/
						}
					},
					fail: (res) => {
						// console.error('======== request fail ========', res)
						utils.toast("网络不给力，请稍后再试~")
						reject(res)
					},
					complete: function(res) {
						// console.log('封装request complete', res)
						// if (loadding && !hideLoading) {
						// 	uni.hideLoading()
						// }
						if (!hideLoading) {
							uni.hideLoading()
						}
						clearTimeout(utils.delayed)
						utils.delayed = null;
						if (res.statusCode === 200) {
							
						} else {
							utils.toast('服务器开小差了~' + res.statusCode);
						}
					}
				})
			}
		})
	},
	//设置token
	setToken: function(token) {	
		// uni.setStorageSync(tokenKey, token)
		vk.setVuex('$user.token', token)
	},
	//获取token
	getToken: function() {
		// return uni.getStorageSync(tokenKey)
		return vk.getVuex('$user.token');
	},
}

module.exports = {
	interfaceUrl: utils.interfaceUrl,
	request: utils.request,
	setToken: utils.setToken,
	getToken: utils.getToken,
	toLogin: utils.toLogin,
}
